package droid.frame.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.EditText;
import droid.frame.libcore.R;
import droid.frame.utils.lang.Str;

/**
 * 格式化输入文本的Edit 默认xxx xxx xxxx...格式
 * 
 * @author kaka<br>
 *         2016-12-29下午6:56:41
 */
@SuppressLint("AppCompatCustomView")
public class FormatEditText extends EditText implements TextWatcher {

	private int type;

	public FormatEditText(Context context) {
		super(context);
		initEdit(context, null);
	}

	public FormatEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		initEdit(context, attrs);
	}

	public FormatEditText(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		initEdit(context, attrs);
	}

	private void initEdit(Context context, AttributeSet attrs) {
		if (attrs != null) {
			TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.FormatEditText);
			type = typedArray.getInt(R.styleable.FormatEditText_type, -1);
			typedArray.recycle();
		}
		addTextChangedListener(this);
	}

	@Override
	public void afterTextChanged(Editable s) {
		if (type == -1) {
			return;
		}
		removeTextChangedListener(this);
		if (type == 1) {
			Str.format(s, 3, 6);
		} else if (type == 2) {
			Str.format(s, 3, 7);
		}
		addTextChangedListener(this);
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {

	}

	@Override
	public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
	}

	/**
	 * 为了获取text字符间不带空格，使用getTextStr()
	 */
	@Deprecated
	@Override
	public Editable getText() {
		return super.getText();
	}

	public String getTextStr() {
		String text = getText().toString();
		return Str.strClearEmpty(text);
	}
}
